import os
from difflib import SequenceMatcher
import tkinter as tk
from tkinter import filedialog, messagebox, ttk

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

def find_similar_files(directory, similarity_threshold=0.9):
    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    similar_files = []

    for i in range(len(files)):
        for j in range(i + 1, len(files)):
            file_name_i = os.path.splitext(files[i])[0]
            file_name_j = os.path.splitext(files[j])[0]
            similarity = similar(file_name_i, file_name_j)
            if similarity >= similarity_threshold:
                similar_files.append((files[i], files[j], similarity))
    
    return similar_files

def select_directory():
    directory = filedialog.askdirectory()
    if directory:
        directory_var.set(directory)
        update_similar_files_list(directory)

def update_similar_files_list(directory):
    similar_files_tree.delete(*similar_files_tree.get_children())
    similar_files = find_similar_files(directory)
    for file_pair in similar_files:
        similar_files_tree.insert('', 'end', values=(file_pair[0], file_pair[1], f"{file_pair[2]:.2%}"))
def choose_file_to_keep(file_path1, file_path2):
    """根据文件大小选择保留哪个文件，保留较大的那个"""
    size1 = os.path.getsize(file_path1) if os.path.exists(file_path1) else 0
    size2 = os.path.getsize(file_path2) if os.path.exists(file_path2) else 0
    if size1 >= size2:
        return file_path2  # 删除较小的文件2
    else:
        return file_path1  # 删除较小的文件1

def delete_selected_files():
    selected_items = similar_files_tree.selection()
    if not selected_items:
        messagebox.showwarning("警告", "请选择要删除的文件")
        return
    
    confirm = messagebox.askyesno("确认删除", "确定要删除所选文件吗？")
    if not confirm:
        return

    for item in selected_items:
        try:
            file1, file2, _ = similar_files_tree.item(item, 'values')
            file_path1 = os.path.join(directory_var.get(), file1)
            file_path2 = os.path.join(directory_var.get(), file2)

            file_to_delete = choose_file_to_keep(file_path1, file_path2)
            
            if os.path.exists(file_to_delete):
                os.remove(file_to_delete)
                deleted_file = os.path.basename(file_to_delete)
                messagebox.showinfo("成功", f"已删除: {deleted_file}")
            else:
                messagebox.showwarning("警告", f"文件不存在: {os.path.basename(file_to_delete)}")

            # Update the treeview after deletion
            similar_files_tree.delete(item)
        except Exception as e:
            messagebox.showerror("错误", f"无法删除文件: {e}")

# GUI setup
root = tk.Tk()
root.title("查找并删除相似文件")

frame = ttk.Frame(root, padding="10")
frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

directory_var = tk.StringVar()

ttk.Label(frame, text="选择目录:").grid(column=0, row=0, sticky=tk.W)
ttk.Entry(frame, textvariable=directory_var, width=50).grid(column=1, row=0, sticky=(tk.W, tk.E))
ttk.Button(frame, text="浏览", command=select_directory).grid(column=2, row=0, sticky=tk.W)

similar_files_tree = ttk.Treeview(frame, columns=('File1', 'File2', 'Similarity'), show='headings')
similar_files_tree.heading('File1', text='文件1')
similar_files_tree.heading('File2', text='文件2')
similar_files_tree.heading('Similarity', text='相似度')
similar_files_tree.grid(column=0, row=1, columnspan=3, sticky=(tk.W, tk.E))

delete_button = ttk.Button(frame, text="删除所选文件", command=delete_selected_files)
delete_button.grid(column=0, row=2, columnspan=3, pady=10)

# Make the grid expandable
for i in range(3):
    root.columnconfigure(i, weight=1)
    root.rowconfigure(i, weight=1)

root.mainloop()
